// pages/User/IndividualBusiness/IndividualBusiness.js

const app = getApp();
import { getSelfEmployedList , laborHasIndustrialList , laborIndustryList , appletSelfEmployedStatus } from '../../../api/employed';
import { throttle } from '../../../utils/util';
const regeneratorRuntime = require('../../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    employedList: [],
    page: 1,
    noMore: false,
    laborCompanyId: '', // 劳务公司ID
    laborCompany: '', // 劳务公司名称
    industry: '', // 行业名称
    laborList: [], // 劳务公司列表
    industryList: [], // 行业列表
    options: [],
    cascaderValue: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.querySelfEmployedList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(wx.getStorageSync('hideSelCompany') == '1'){
      this.setData({
        show: false,
        page: 1,
        noMore: false,
        })
      this.querySelfEmployedList();
      wx.setStorageSync('hideSelCompany', '0');
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
        page: 1,
      })
      this.querySelfEmployedList()
      setTimeout(()=>{
        wx.stopPullDownRefresh({
          success: (res) => {
            wx.showToast({
              title: '刷新成功',
              icon: 'none',
            })
          },
        })
      },1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: throttle(function(){
    if(this.data.isReachBottom){
      this.getData()
    }
  },500),

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 选择企业和行业
  selCompany(){
    this.setData({ 
        laborCompany: '',
        laborCompanyId: '',
        industry: '',
    });
    this.getLaborHasIndustrialList();
  },
  onClose() {
    this.setData({ show: false });
  },
    // 获取个体工商户申请记录
    querySelfEmployedList(){
        let _this = this;
        getSelfEmployedList({page: _this.data.page})
        .then(res => {
            if(res.success){
                let list = _this.data.employedList;
                if(_this.data.page == 1){
                    list = res.data
                }else{
                    list.concat(res.data);
                }
                _this.setData({
                    employedList: list,
                    page: _this.data.page+1,
                })
                if((_this.data.page * 10) >= res.totalCount){
                    _this.setData({
                        noMore : true,
                    })
                }
                console.log(_this.data.employedList,'employedList')
            }else{
                wx.showToast({
                    title: res.errMessage,
                    icon: 'none',
                  })
            }
        })
    },
    // 获取劳务公司列表
    getLaborHasIndustrialList(){
        let _this = this;
        laborHasIndustrialList()
        .then(async res => {
            if(res.success){
                _this.setData({
                    laborList: res.data,
                })
                var list = [];
                for (let index = 0; index < res.data.length; index++) {
                    const element = res.data[index];
                    element['value'] = element.id;
                    element['text'] = element.companyName;
                    list.push(element);
                }
                _this.setData({
                    options: list,
                    show: true,
                })
                console.log(_this.data.options,'options')
            }else{
                wx.showToast({
                    title: res.errMessage,
                    icon: 'none',
                })
            }
        })
    },
    // 获取劳务公司下的园区列表
    getLaborIndustryList(laborCompanyId){
        let _this = this;
        return new Promise((resolve,reject) => {
            laborIndustryList({laborCompanyId:laborCompanyId,})
            .then(res => {
                if(res.success){
                    var arr = [];
                    for (let index = 0; index < res.data.length; index++) {
                        const item = res.data[index];
                        var obj = {
                            'value': item,
                            'text': item,
                        }
                        arr.push(obj);
                    }
                    resolve(arr);
                }else{
                    resolve([]);
                }
            })
          })
    },
    async onChange(e) {
        const { value , tabIndex } = e.detail;
        console.log(value,'value',tabIndex);
        if(tabIndex == 0){
          let laborCompany = this.data.options.find(item => item.id == value);
          var appletStatus = await this._appletSelfEmployedStatus({laborCompanyId: value});
          if(!appletStatus && laborCompany.industrialParkRegisterType == '2'){
            wx.showModal({
              title: '温馨提示',
              showCancel: false,
              content: '请先承接该公司下的任务，并完成合同签署后，方可申请注册个体工商户',
              complete: (res) => {
                if (res.confirm) {
                  
                }
              }
            });
            return;
          }
            var children = await this.getLaborIndustryList(value);
            console.log(children,'children')
            var index = this.data.options.findIndex(item => item.id == value);
            var opt = this.data.options;
            opt[index].children = children;
            this.setData({
                options: opt,
                laborCompanyId: value,
            })
        }else{
            this.setData({
                industry: value,
            })
            wx.navigateTo({
              url: `/pages/User/IndustrialParkDetail/IndustrialParkDetail?laborCompanyId=${JSON.stringify(this.data.laborCompanyId)}&industry=${encodeURIComponent(JSON.stringify(this.data.industry))}&isAdd=1`,
            })
        }
        // if (value === this.data.options[0].value) {
        // setTimeout(() => {
        //     const children = [
        //     { text: '杭州市', value: '330100' },
        //     { text: '宁波市', value: '330200' },
        //     ];
        //     this.setData({
        //     'options[0].children': children,
        //     })
        // }, 500);
        // }
    },
    // 页面跳转
    goNext(e){
        let type = e.target.dataset.type||e.currentTarget.dataset.type;
        let url = e.target.dataset.name||e.currentTarget.dataset.name;
        let item = e.target.dataset.item||e.currentTarget.dataset.item;
        // return
        if(item){
            if(type == 1){
            wx.switchTab({
                url: `${url}`,
            })
            }else{
            wx.navigateTo({
                url: `${url}?item=${JSON.stringify(item)}`,
            })
            }
        }else{
            if(type == 1){
            wx.switchTab({
                url: `${url}`,
            })
            }else{
            wx.navigateTo({
                url: `${url}`,
            })
            }
        }
    },
    // 查询是否和劳务公司签约
    _appletSelfEmployedStatus({laborCompanyId}){
      return new Promise((resolve,reject) => {
        appletSelfEmployedStatus({LaborCompanyId: laborCompanyId})
        .then(res => {
          if(res.success){
            resolve(res.data);
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      })
    },
})